<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-left">
        <el-input
          size="mini"
          v-model="searchKey"
          placeholder="项目名称/内容/进度/类型/负责人"
          style="width: 250px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @input="handleFilter"
        />
        <el-input
          size="mini"
          v-model="orderId"
          placeholder="订单编号"
          style="width: 120px;margin-left: 10px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @input="handleFilter"
        />
      </div>
      <div class="filter-right">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleAdd">
          新增项目
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="pageList"
      border
      fit
      stripe
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" fixed/>
      <el-table-column
        prop="project_name"
        label="项目名称"
        align="left"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column label="创建方式" align="center" width="120">
        <template slot-scope="{ row }">
            <el-tag v-if="row.is_import == 1" key="氚云导入">氚云导入</el-tag>
            <el-tag v-else key="OA创建" type="warning">OA创建</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="project_progress"
        label="项目进度"
        align="center"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="project_type"
        label="项目类型"
        align="center"
        width="120"
      >
      </el-table-column>
      <el-table-column label="订单编号" prop="order_id" align="center" width="120">
      </el-table-column>
      <el-table-column label="关联订单" align="center" width="120">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="examine(row.id)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      
      <el-table-column
        prop="brand_name"
        label="品牌名称"
        align="center"
        width="150"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="user_name"
        label="负责人名称"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleDetails(scope.row)"
            type="text"
            size="small"
            style="color: green"
            >查看详情</el-button
          >
          <el-button @click="handleModify(scope.row)" type="text" size="small"
            >修改</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="small"
            v-if="checkPermission(['admin'])"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getPageList"
    />

    <!-- 新增项目 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="550px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="项目名称"   label-width="100px" prop="projectName">
          <el-input
            v-model="form.projectName"
            :disabled="form.is_import == 1"
            autocomplete="off"
            maxlength="50"
            @input="changeValue('projectName', '50')"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="项目进度"
          label-width="100px"
          prop="projectProgress"
        >
          <el-select
            v-model="form.projectProgress"
            clearable
            filterable
            placeholder="请选择项目进度"
            style="width: 100%"
          >
            <el-option
              v-for="item in projectLimit"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目类型" label-width="100px" prop="projectType">
          <el-select
            v-model="form.projectType"
            filterable
            clearable
            placeholder="请选择项目类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in projectType"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属品牌" label-width="100px">
          <el-select
            v-model="form.brandName"
            filterable
            clearable
            placeholder="请选择归属品牌"
            style="width: 100%"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.brand_name"
              :value="item.brand_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="关联订单" label-width="100px">
          <el-select
            v-model="form.orderId"
            multiple
            placeholder="请选择关联订单"
            style="width: 100%"
            clearable
            @change="bindChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.order_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="项目负责人" label-width="100px">
          <!-- <treeselect
            v-model="value"
            :multiple="false"
            :options="rootOptions"
            :load-options="loadOptions"
            :disable-branch-nodes="true"
            placeholder="选择项目负责人"
            @select="onSelect"
            @deselect="onDeselect"
          /> -->
          <el-select
            ref="optionRef"
            v-model="form.userId"
            filterable
            placeholder="请选择项目负责人"
            style="width: 100%"
          >
            <el-option
              v-for="item in orderOptions"
              :key="item.unionid"
              :label="item.name"
              :value="item.unionid"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目内容" label-width="100px">
          <el-input
            type="textarea"
            rows="5"
            maxlength="200"
            resize="none"
            @input="changeValue('projectContent', '200')"
            placeholder="请输入内容"
            v-model="form.projectContent"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单信息 -->
    <el-dialog title="订单信息" :visible.sync="OrderFormVisible" width="550px">
      <div style="display: flex; justify-content: space-between">
        <el-select
          v-model="orderIDs"
          placeholder="请选择关联订单"
          style="width: 80%"
          filterable
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.order_name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-button type="primary" @click="handlebinding">绑定</el-button>
      </div>
      <el-table :data="orderData">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="order_name"
          label="订单名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="order_id"
          label="订单ID"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              @click="handleRescind(scope.row)"
              type="text"
              size="small"
              >解绑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import {
  getProjPage,
  createdProj,
  updatedProj,
  delProjInfo,
  getDeptLists,
  getDeptUserLists,
  getUserLists,
  getProjById,
  updateProjOrderContact
} from "@/api/project";
import { getAllBrandsPage } from "@/api/brand";
import { getDataByCode, checkUserToken } from "@/api/user";
import { getOrderPage } from "@/api/order";
import { curentTime } from "@/filters/index";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect";
import checkPermission from "@/utils/permission"; // 权限判断函数
export default {
  name: "Shop",
  components: { Pagination, Treeselect },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 项目数据
      pageList: [],
      // 项目总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      searchKey: "",
      orderId: "",
      // 表单控制
      dialogFormVisible: false,
      dialogCharge: false,
      OrderFormVisible: false,
      // 表单标题
      title: "",
      // 表单参数
      form: {
        brandName: "",
        projectName: "",
        projectContent: "",
        projectProgress: "开发中",
        projectType: "项目开发",
        userId: "",
        userName: "",
        is_import:''
      },
      orderIDs: "",
      // 表单检验
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectProgress: [
          { required: true, message: "请选择项目进度", trigger: "change" },
        ],
        projectType: [
          { required: true, message: "请选择项目类型", trigger: "change" },
        ],
      },
      // 项目类型
      projectType: [],
      // 项目进度
      projectLimit: [],

      // 项目负责人
      value: null,
      rootOptions: [],
      // 关联订单
      options: [],
      order_id: "",
      orderOptions: [],
      // 订单信息
      orderData: [],
      projectId: "",
      // 查询更新订单信息
      projecId: "",
      // 品牌方信息
      brandList: [],
    };
  },
  async created() {
    await this.getPageList();
    // this.getRootModels();

    // 获取订单
    getOrderPage({ pageNum: 1, pageSize: 200 }).then((res) => {
      this.options = res.data.lists;
    });

    // 获取项目类型
    getDataByCode({ code: "ProjectType,ProjectProgress,OnJobUser" }).then((res) => {
      this.projectType = res.data.ProjectType || null;
      this.projectLimit = res.data.ProjectProgress || null;
      this.orderOptions = res.data.OnJobUser || null;
    });

    // 获取品牌方信息
    getAllBrandsPage().then((res) => {
      this.brandList = res.data;
    });
  },
  methods: {
    checkPermission,

    getRootModels() {
      //初始化数据 只加载根节点
      getDeptLists({ deptId: 1 }).then((response) => {
        let options = Object.values(response.data);
        options.pop();
        for (let index of options) {
          let modeInfo = {};
          modeInfo.id = index.dept_id;
          modeInfo.label = index.name;
          modeInfo.children = null;
          this.rootOptions.push(modeInfo);
        }
      });
    },

    /** 加载子节点数据 **/
    loadOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        //加载点击节点的子节点
        getDeptLists({ deptId: parentNode.id }).then((response) => {
          let datas = Object.values(response.data);
          datas.pop();
          let arr = [];
          for (let index of datas) {
            let chiledModeInfo = {};
            chiledModeInfo.id = index.dept_id;
            chiledModeInfo.label = index.name;
            chiledModeInfo.children = null;
            arr.push(chiledModeInfo);
          }
          parentNode.children = arr;

          if (parentNode.children.length == 0) {
            getDeptUserLists({ deptId: parentNode.id }).then((response) => {
              let userArr = [];
              for (let index of response.data.list) {
                let chiledUser = {};
                chiledUser.id = index.userid;
                chiledUser.label = index.name;
                chiledUser.children = {};
                userArr.push(chiledUser);
              }
              parentNode.children = userArr;
            });
          }
        });

        callback();
      }
    },

    onSelect(node) {
      this.form.userId = node.id;
      this.form.userName = node.label;
    },

    onDeselect(node) {
      // console.log(node, "Deselect");
    },

    // 按需查询
    async handleFilter() {
      this.listQuery.searchKey = this.searchKey;
      this.listQuery.orderId = this.orderId;
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询项目数据
    async getPageList() {
      try {
        const res = await getProjPage(this.listQuery);
        if(this.orderId){
          this.pageList = [];
          res.data.items.forEach(item=>{
            if(item.ProjectRecords && item.ProjectRecords.length){
              item.ProjectRecords.forEach(el=>{
                this.pageList.push({...el,order_id:item.order_id})
              })
            }
          })
          this.total = this.pageList.length;
        }else{
          this.pageList = [];
          res.data.items.forEach(item=>{
            if(item.OrdRecords){
              item.order_id = item.OrdRecords.length?item.OrdRecords[0].order_id : ""
            }
            this.pageList.push(item)
          })
          this.total = res.data.totalPages;
        }
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 提交表单信息
    submitForm(formName) {
      // 负责人
      if (this.form.userId) {
        this.form.userName = this.$refs.optionRef.selected.label;
        this.form.userId = this.$refs.optionRef.selected.value;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updatedProj(this.form).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          } else {
            createdProj(this.form).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          }
        } else {
          return false;
        }
      });
    },

    // 修改订单信息
    submitOrder() {},

    // 取消
    resetForm(formName) {
      this.dialogFormVisible = false;
    },

    // 订单信息取消
    orderForms() {
      this.OrderFormVisible = false;
    },

    // 新增项目
    handleAdd() {
      checkUserToken().then((res) => {
        if(res.data) {
          this.title = "新增项目";
          this.$delete(this.form, "id");
          this.form.projectName = "";
          this.form.projectContent = "";
          this.form.userId = null;
          this.form.userName = "";
          this.order_id = "";
          this.form.brandName = "";
          this.$nextTick(() => {
            this.$refs["form"].resetFields();
          });
          this.dialogFormVisible = true;
        }
      })
    },

    // 查看详情
    handleDetails(row) {
      this.$router.push({ path: "/project/details", query: { id: row.id } });
    },

    // 修改
    handleModify(row) {
      console.log(row,'rowrowrow')
      this.title = "修改项目";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.form.id = row.id;
        this.form.brandName = row.brand_name;
        this.form.projectName = row.project_name;
        this.form.projectContent = row.project_content;
        this.form.projectProgress = row.project_progress;
        this.form.projectType = row.project_type;
        this.form.is_import = row.is_import
        if (row.order_id) {
          let arr = row.order_id.split(",");
          this.form.orderId = arr.map(Number);
        }
        // 负责人
        if (row.user_id) {
          this.form.userId = row.user_id;
        }
        console.log(this.form,'this.form')
      });
    },

    // 多选订单
    bindChange(e) {
      if (e.length > 5) {
        this.$message.warning("最多只能绑定5个订单");
        this.form.orderId.splice(-1);
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm("此操作将删除该项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delProjInfo(row.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getPageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 查看订单
    examine(id) {
      getProjById({ id: id }).then((res) => {
        console.log("res", res)
        // 项目id
        this.projectId = res.data.project.id;
        this.orderData = res.data.orderList;
      });
      this.OrderFormVisible = true;
    },

    // 解除绑定
    handleRescind(row) {
      let data = {
        projId: this.projectId,
        orderId: row.id,
        isBind: 0,
      };
      updateProjOrderContact(data).then((res) => {
        this.$message({
          message: "解绑成功",
          type: "success",
        });
        this.examine(this.projectId);
      });
    },

    // 绑定
    handlebinding() {
      let data = {
        projId: this.projectId,
        orderId: this.orderIDs,
        isBind: 1,
      };
      if (this.orderIDs) {
        updateProjOrderContact(data).then((res) => {
          this.$message({
            message: "绑定成功",
            type: "success",
          });
          this.orderIDs = "";
          this.examine(this.projectId);
        });
      } else {
        this.$message({
          message: "请选择订单",
          type: "error",
        });
      }
    },

    // 输入字数限制
    changeValue(attr, byte) {
      let value = this.form[attr]; //校验的字段
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let maxLimitStr = byte; //25个汉字
      let pass = true;
      let substringStr = "";
      let length = 0;
      let strArr = value.split("");
      strArr.map((str) => {
        if (pass) {
          if (cnReg.test(str)) {
            //中文
            length++;
          } else {
            //英文
            length += 0.5;
          }
          //大于最大限制的时候
          if (length > maxLimitStr) {
            pass = false;
            //将校验的字符截取返回
            this.form[attr] = substringStr;
          } else {
            substringStr += str;
          }
        }
      });
      return pass;
    }
  },
};
</script>


<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}

.Charge-left {
  width: 375px;
  // height: 800px;
}

.Charge-left {
  width: 525px;
  // height: 800px;
}
</style>

<style>
.el-tooltip__popper {
  max-width: 30%;
}
.project_name{
  display: flex;
  align-content: center;
  justify-content: space-between;
}
</style>
